<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Croakd
 */
class App_Controller extends Core_Controller {
	
	public function index()
	{
		$this->view = new View('main');
		$this->view->render(TRUE);
	}
	
	public function parse()
	{
		$filter		  = '- ';
		$username 	= 'carloselias';
		$tweets			= 200;
		$url  			= 'http://twitter.com/statuses/user_timeline.json?count='.$tweets.'&screen_name='.$username;
		$data   		= '';
		$curl				= new Curl_Cache($url);
		$curl->setCachePath(Kohana::config('cache.default.params'));
		$curl->setTtl(3600);
		$data				= json_decode($curl->getData());	 
	
		foreach ($data as $tweet) 
		{
			$text = $tweet->text;
			$pattern = '(^'.$filter.'.*)';
			if (preg_match($pattern, $text)) {		
//				$text = preg_replace($pattern, '', $text);
				$text_arr = explode(":", $text);
				$id = $tweet->id;
				$title = $text_arr[0];
//			$description = str_replace($title.':', '', $text);
				$description = $text;
				$link = 'http://twitter.com/'.$username.'/status/'.$id;
				$pubDate = $tweet->created_at;
				$post_count = ORM::factory('post')->where('tweet_id', $id)->count_all();

				if ($post_count == 0) {
					$post = ORM::factory('post');
					$post->user_id 		= 1;
					$post->tweet_id		= $id;
					$post->title 			= $title;
					$post->content 		= $description;
					$post->author			= $username;
					$post->link 			= $link;
					$post->created_at = date('Y-m-d H:i:s');
					$post->save();
				}

			}
			
		}		
	}
	
	public function feed($format = NULL)
	{
		$info = array('notes' => 'Created by Croakd');
		$posts = ORM::factory('post')->orderby('created_at', 'DESC')->find_all();
		$items = array();
		foreach ($posts as $post)
		{
			$items[] = array(
				    'title' 			=> $post->title,
				    'link' 				=> $post->link,
				    'description' => $post->content,
				    'author' 			=> $post->author,
				    'pubDate' 		=> date("c", strtotime($post->created_at)),
				);
		}
		
		switch ($format) {
			default:
				echo feed::create($info, $items);	
				break;
			case 'json':
				echo json_encode($items);
				break;
		}
	}

}
